<template>
  <div class="my_quill">
    <!-- 图片上传组件辅助-->
    <el-upload
      class="avatar-uploader"
      :action="define.baseImageUploadURL"
      :headers="headers"
      :show-file-list="false"
      accept="image/*"
      :on-success="uploadSuccess"
    >
    </el-upload>

    <quill-editor
      :disabled="disabled"
      class="my_quill_group"
      v-model="value"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
      @ready="onEditorReady($event)"
    >
    </quill-editor>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// 导入自定义样式 一定要在原插件css下面引入  (看上面修改字体字号)
import "@/assets/scss/base_quill_editor.css";
// 导入修改字体及字号 工具栏相关配置 设置工具栏中文提示（详细内容看下边）
import { titleConfig, toolbarOptions } from "@/utils/base-quill-editor";

export default {
  name: "BaseQuillEdit",
  components: {
    quillEditor,
  },
  props: {
    /**
     * @description 绑定值
     * */
    value: {
      type: String,
      default: "",
    },
    /**
     * @description 是否禁用
     * */
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      headers: {
        Authorization: this.common.getStorage("token") || "",
        token: this.common.getStorage("token") || "",
      },
      editorOption: {},
    };
  },
  created() {
    if (this.disabled) {
      this.editorOption = {
        modules: {
          imageDrop: true, // 图片拖拽
          imageResize: {
            // 放大缩小
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
          toolbar: false,
        },
        placeholder: "请输入正文....",
        theme: "snow", //主题 snow：有工具栏的；bubble：只有文本域的
      };
    } else {
      this.editorOption = {
        modules: {
          imageDrop: true, // 图片拖拽
          imageResize: {
            // 放大缩小
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
          toolbar: {
            container: toolbarOptions, //工具栏相关配置
            handlers: {
              image: function (value) {
                if (value) {
                  // 调用element的图片上传组件
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
        placeholder: "请输入正文....",
        theme: "snow", //主题 snow：有工具栏的；bubble：只有文本域的
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.setTitleConfig();
    });
  },
  methods: {
    // 失去焦点事件
    onEditorBlur(quill) {
      //   console.log("editor blur!", quill);
      // this.$emit('on-editor-blur', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      //   console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      //   console.log("editor ready!", quill);
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      //   console.log("内容改变事件", quill, html, text);
      this.$emit("change", html);
    },
    //设置工具栏中文提示
    setTitleConfig() {
      for (const item of titleConfig) {
        const tip = document.querySelector(".quill-editor " + item.Choice);
        if (!tip) continue;
        tip.setAttribute("title", item.title);
        // 更改提示信息的内容
      }
    },
    uploadSuccess(res) {
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;

      // 如果上传成功
      if (res) {
        // 获取光标所在位置 .index
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        this.$message.error("图片插入失败！");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.my_quill {
  // display: flex;
  .avatar-uploader {
    display: none;
  }
  & ::v-deep .ql-snow .ql-editor {
    min-height: 150px !important;
  }
}
</style>